package com.ruix.app.ui.user;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.OSS;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.OssTokenMapper;
import com.ruix.app.mapper.UserMapper;
import com.ruix.app.model.Notice;
import com.ruix.app.model.OssToken;
import com.ruix.app.model.User;
import com.ruix.app.model.UserInfo;
import com.ruix.app.model.WXUserInfo;
import com.ruix.app.network.ALUploadFileParam;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.main.MainActivity;
import com.ruix.app.ui.stratum.notice.NoticeDetailActivity;
import com.ruix.app.ui.user.address.ProvinceChoseActivity;
import com.ruix.app.util.GlideUitl;
import com.ruix.app.util.RegUtil;
import com.ruix.app.util.SoftInputUtil;
import com.ruix.app.widget.addr.ProviceChooseView;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/4/12.
 */

public class ImportUserInfoActivity extends BaseActivity implements View.OnClickListener, ProviceChooseView.ProviceChooseActionLisenler {


    private EditText usernameEditText, userVocationEditText, userCompanyEditText;
    private TextView userGenderText, userAddressText;
    private UserInfo userInfo;
    private int gender = 1; //默认性别
    private boolean chosedGender;
    private WXUserInfo wxUserInfo;
    private OSS ossClient;
    private OssToken ossToken;
    private String avatarLocalPath;
    private String from;

    public static Intent newIntent(Context context, String from,WXUserInfo wxUserInfo) {
        Intent intent = new Intent(context, ImportUserInfoActivity.class);
        intent.putExtra("from", from);
        intent.putExtra("wxuserinfo", wxUserInfo);
        return intent;
    }


    @Override
    protected int loadViewLayout() {
        return R.layout.activity_import_user_info;
    }

    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected void initView() {
        usernameEditText = (EditText) findViewById(R.id.et_user_name);
        userGenderText = (TextView) findViewById(R.id.et_user_gender);
        userGenderText.setText("男");
        userVocationEditText = (EditText) findViewById(R.id.et_user_vocation);
        userCompanyEditText = (EditText) findViewById(R.id.et_user_company);
        userAddressText = (TextView) findViewById(R.id.et_user_address);

        usernameEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        userVocationEditText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        userCompanyEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
//        loadOssTokenWithCache();
    }

    private void updateView() {

    }

    private void updateGender() {
        if (gender == 1) {
            userGenderText.setText(R.string.male);
        } else {
            userGenderText.setText(R.string.female);
        }
    }

    @Override
    protected void initLocalData() {
        userInfo = new UserInfo();
        Intent intent = getIntent();
        if (intent != null) {
            from = intent.getStringExtra("from");
            wxUserInfo = (WXUserInfo) intent.getSerializableExtra("wxuserinfo");
        }

        if (wxUserInfo != null) {
            if (wxUserInfo.getSex() == 1){ //1 为男 2为女
                gender = 1;
            } else {
                gender = 0;
            }
            userInfo.setSex(gender);
//            userInfo.setAvatarPath(wxUserInfo.getHeadimgurl());
            userInfo.setName(wxUserInfo.getNickname());
            usernameEditText.setText(wxUserInfo.getNickname());
//            String locate = "" + wxUserInfo.getProvince() + wxUserInfo.getCity();
//            userInfo.setLocate(locate);
//            userAddressText.setText(locate);
        } else if (from != null && "SplashActivity".equals(from)) {
            User user = UserManager.getCurrentUser();
            if (user.getGender() == 1){ //1 为男 0为女
                gender = 1;
            } else {
                gender = 0;
            }
            userInfo.setSex(gender);
            if (!TextUtils.isEmpty(user.getName())) {
                userInfo.setName(user.getName());
                usernameEditText.setText(user.getName());
            }
        }
        updateGender();

    }

    @Override
    protected void initListener() {
        findViewById(R.id.close_page).setOnClickListener(this);
        findViewById(R.id.btn_enter_app).setOnClickListener(this);
        findViewById(R.id.rl_gender_contain).setOnClickListener(this);
        findViewById(R.id.rl_address_contain).setOnClickListener(this);
        usernameEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    SoftInputUtil.hideSoftInput(usernameEditText);
                    return true;
                }
                return false;
            }
        });
        userCompanyEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    SoftInputUtil.hideSoftInput(usernameEditText);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_page:
                finish();
                break;

            case R.id.btn_enter_app:
                submitUserinfoWithAvatar();

                break;

            case R.id.rl_gender_contain:
                choseGender();
                break;

            case R.id.rl_address_contain:
//                showProviceChooseView();
                provinceChoose();
                break;


        }
    }

    private void submitUserinfoWithAvatar(){
//        if (!TextUtils.isEmpty(userInfo.getAvatarPath())){
//            submitUserInfo(); //下载并上传成功
//        } else if (!TextUtils.isEmpty(avatarLocalPath)){
//            uploadAvatarAndSubmit(avatarLocalPath); //下载成功过
//        } else if (!TextUtils.isEmpty(wxUserInfo.getHeadimgurl())) {
//            downLoadAvatarAndSumitUserInfo(); //下载上传头像 并提交信息
//        }else {
            submitUserInfo();
//        }
    }

    private void submitUserInfo() {
        String userName = usernameEditText.getText().toString().trim();
        String vocation = userVocationEditText.getText().toString().trim();
        String company = userCompanyEditText.getText().toString().trim();

        if (TextUtils.isEmpty(userName)
                || "".equals(userName)) {
            showErrorTip("请输入姓名");
            return;
        }

        if (TextUtils.isEmpty(vocation)
                || "".equals(vocation)) {
            showErrorTip("请输入职业");
            return;
        }


        if (RegUtil.isLessThanLength(userName,2) || RegUtil.isMoreThanLength(userName,20)){
            showErrorTip("请输入2-20个字符的用户名");
            return;
        }

        if (RegUtil.isLessThanLength(vocation,2) || RegUtil.isMoreThanLength(vocation,20)){
            showErrorTip("请输入2-20个字符的职业名称");
            return;
        }

        if (!TextUtils.isEmpty(company)) {
            if (RegUtil.isLessThanLength(company, 2) || RegUtil.isMoreThanLength(company, 20)) {
                showErrorTip("请输入2-20个字符的公司名称");
                return;
            }
            userInfo.setCompany(company);
        }

        userInfo.setPosition(vocation);
        userInfo.setName(userName);


        showLoading();
        RequestFactory.editUserinfo(userInfo, new UserMapper(), new RXObserver<User>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(User value) {
                showSuccessTip("绑定成功");
                if (value != null && !TextUtils.isEmpty(value.getID())) {
                    UserManager.sharedInstance().setCurrentUser(value);
                }
                bindSuccess();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }


            @Override
            public void onComplete() {
                dismissLoading();
            }
        });

    }

    private void bindSuccess() {
        if (from != null && "SplashActivity".equals(from)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            this.finish();
        } else {
            setResult(RESULT_OK);
            finish();
        }
    }

    private void choseGender() {
        startActivityForResult(GenderChoseActivity.newIntent(this, gender), 1000);
    }

    private void provinceChoose() {
        startActivityForResult(ProvinceChoseActivity.newIntent(this, ""), 2000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1000 && resultCode == 1002) {
            if (data != null) {
                chosedGender = true;
                gender = data.getIntExtra("gender", 0);
                userInfo.setSex(gender);
                updateGender();
            }
        } else if (requestCode == 2000 && resultCode == 10013) {
            if (data != null) {
                String resion = data.getStringExtra("resion");
                userInfo.setLocate(resion);
                userAddressText.setText(resion);

            }
        }
    }




    @Override
    public void positiveAction(String provice, String city, String distric) {
        String address = provice + city;
        if (!"其他".equals(distric)) {
            address += distric;
        }
        userInfo.setLocate(address);
        userAddressText.setText(address);
    }

    @Override
    public void negativeAction() {
    }
    
    public void uploadAvatar(String filePath){
        //
//        wxUserInfo.getHeadimgurl()
        ALUploadFileParam param = new ALUploadFileParam();
        param.setUid(UserManager.getCurrentUser().getID());
        param.addPathe(filePath);
        param.setOssClient(ossClient);
        param.setOssToken(ossToken);
        RequestFactory.uploadFileToALY(param, new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                //
                if(value != null && value.size() > 0){
                    userInfo.setAvatarPath(value.get(0));
                }
                //
//                submitUserInfo();

            }

            @Override
            public void onError(Throwable e) {
//                showErrorTip(e.getMessage());
//                dismissLoading();
//                submitUserInfo();
            }

            @Override
            public void onComplete() {

            }
        });
    }


    public void uploadAvatarAndSubmit(String filePath){
        ALUploadFileParam param = new ALUploadFileParam();
        param.setUid(UserManager.getCurrentUser().getID());
        param.addPathe(filePath);
        param.setOssClient(ossClient);
        param.setOssToken(ossToken);
        RequestFactory.uploadFileToALY(param, new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                //
                if(value != null && value.size() > 0){
                    userInfo.setAvatarPath(value.get(0));
                }
                //
                submitUserInfo();

            }

            @Override
            public void onError(Throwable e) {
                submitUserInfo();
            }

            @Override
            public void onComplete() {

            }
        });
    }




    private void loadOssTokenWithCache(){
        String uid = UserManager.getCurrentUser().getID();
        ossToken =  CacheFactory.loadOssToken(uid);
        if (ossToken != null && !TextUtils.isEmpty(ossToken.getSecurityToken())){
            buildOssClient();
        } else {
            loadOssToken();
        }
    }

    private void buildOssClient(){
        if (ossToken != null) {
            ossClient = ALUploadFileParam.loadOSSClient(this, ossToken);
        }
    }

    private void loadOssToken(){
        RequestFactory.getOssToken(new OssTokenMapper(), new RXObserver<OssToken>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OssToken value) {
                if (value != null && !TextUtils.isEmpty(value.getSecurityToken())){
                    ossToken = value;
                    buildOssClient();
                }
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });
    }




    private void downLoadAvatar(){
        new Thread(){
            @Override
            public void run() {
                Glide.with(RuiApplication.getAppContext()).load(wxUserInfo.getHeadimgurl()).downloadOnly(new SimpleTarget<File>() {
                    @Override
                    public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                        avatarLocalPath = resource.getAbsolutePath();
                        uploadAvatar(avatarLocalPath);
                    }
                });
            }
        }.start();
    }

    private void downLoadAvatarAndSumitUserInfo(){
        new Thread(){
            @Override
            public void run() {
                Glide.with(RuiApplication.getAppContext()).load(wxUserInfo.getHeadimgurl()).downloadOnly(new SimpleTarget<File>() {
                    @Override
                    public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                        avatarLocalPath = resource.getAbsolutePath();
                        uploadAvatarAndSubmit(avatarLocalPath);
                    }
                });
            }
        }.start();
    }

}
